package com.ruoyi.platform.system.user.manager.role;

import com.ruoyi.platform.system.role.dao.RoleRdbDAO;
import com.ruoyi.platform.system.role.pojo.RoleDO;
import com.ruoyi.platform.system.user.dao.role.UserRoleDAO;
import com.ruoyi.platform.system.user.pojo.role.UserRoleDO;
import com.ruoyi.platform.system.user.pojo.role.UserRoleDTO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色
 * @author lcf
 */
@Component
public class UserRoleManager {

    @Autowired
    private UserRoleDAO userRoleRdbDAO;
    @Autowired
    private RoleRdbDAO roleRdbDAO;

    /**
     * 获取用户角色id列表
     */
    public List<Long> getUserRoleIdList(long userId) {
        List<UserRoleDO> userRoleList = userRoleRdbDAO.selectByUserRole(new UserRoleDO(userId));
        if (CollectionUtils.isEmpty(userRoleList)) {
            return Collections.emptyList();
        }

        return userRoleList.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
    }

    /**
     * 获取用户角色列表
     */
    public List<UserRoleDTO> getUserRoleList(List<Long> userIdList) {
        List<UserRoleDO> userRoleList = userRoleRdbDAO.selectByUserIdList(userIdList);
        if (CollectionUtils.isEmpty(userRoleList)) {
            return Collections.emptyList();
        }

        List<Long> roleIdList = userRoleList.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        List<RoleDO> roleList = roleRdbDAO.selectRoleByPrimaryKeyList(roleIdList);

        if (CollectionUtils.isEmpty(roleList)) {
            return Collections.emptyList();
        }

        return userRoleList.stream().map(x -> new UserRoleDTO(x, roleList)).collect(Collectors.toList());
    }

    /**
     * 用户设置角色
     */
    public void editUserRole(long userId, List<Long> roleIdList) {
        userRoleRdbDAO.delByUserId(userId);

        if (CollectionUtils.isNotEmpty(roleIdList)) {
            List<RoleDO> roleList = roleRdbDAO.selectRoleByPrimaryKeyList(roleIdList);
            if (CollectionUtils.isEmpty(roleList)) {
                return;
            }

            List<UserRoleDO> userRoleList = new ArrayList<>(roleList.size());
            roleList.forEach(x -> userRoleList.add(new UserRoleDO(userId, x.getRoleId())));
            userRoleRdbDAO.insertUserRoleSelectiveBatch(userRoleList);
        }
    }
}
